package com.boost.cipher.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PasswordFinder;
import org.bouncycastle.util.io.pem.PemObject;

import java.io.File;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;

public class PEMCoder {

    public static KeyPair redKeyPair(File pemFile,char[] password) throws Exception{
        Security.addProvider(new BouncyCastleProvider());
        PEMReader p = new PEMReader(new FileReader(pemFile),new PasswordFinder(){
            public char[] getPassword() {
                                return "123456".toCharArray();
                            }
        });
        KeyPair keyPair = (KeyPair) p.readObject();
        p.close();
        return keyPair;
    }
    public static KeyPair redKeyPair(String pemFile,char[] password) throws Exception{
        return redKeyPair(new File(pemFile),password);
    }
    public static void main(String agr[]) throws Exception {
        KeyPair keyPair = redKeyPair(new File("C:\\Program Files\\OpenSSL-Win32\\bin\\private\\client.key.pem"), null);

        PrivateKey aPrivate = keyPair.getPrivate();

        PublicKey aPublic = keyPair.getPublic();

        System.out.println(aPrivate.getAlgorithm());
        System.out.println(aPublic.getAlgorithm());
        System.out.println(aPublic.getEncoded());

    }
}
